<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/11/23
 * Time: 13:20
 */
declare(strict_types=1);

namespace app\web\middleware;
use app\common\Util\JwtUtil;
use app\web\model\Shop;
use app\web\service\AliService;

class CheckToken{
    public function handle($request, \Closure $next){
        // 登录接口无须验证token
        $token = $request->header('x-token');
        // token丢失
        if(empty($token)){
            //token不存在，重新授权登录
            return json_ok(array('url'=>AliService::getAuthorUrl()),10019);
        }
        $decrypt = think_decrypt($token);
        // token过期判断
        if(empty($decrypt)){
            return json_ok([],10005);
        }

        $payload = JwtUtil::decode($decrypt);
        if($payload === false || empty($payload->shop_id)){
            return json_ok([],10004);
        }
        //取数据
        $session_shop = session("shop_{$payload->shop_id}");
        if(empty($session_shop) || time() > $session_shop['session_expires_time']){
            //无session信息 或 时间过期
            // 实时用户数据
            $shop_model = new Shop();
            $user = $shop_model->where("id='{$payload->shop_id}'")->find();
            if(empty($user)){
                return json_ok([],10006);
            }
            //设置过期时间15分钟
            $user['session_expires_time'] = bcadd(time(),900);
            //存session
            session("shop_{$payload->shop_id}",ObjectToArray($user));
        }
        else{
            //有session信息，返回
            $user = $session_shop;
        }
        $request->user = $user;
        return $next($request);
    }
}